package com.asen.commons.core.jdbc.builder.mysql.filter;

import com.asen.commons.core.jdbc.param.SqlColumn;
import com.asen.commons.core.jdbc.param.SqlContextManager;
import com.asen.commons.core.meta.dao.FilterItem;
import com.asen.commons.core.meta.enums.FilterSymbolEnum;

import java.util.Arrays;
import java.util.Collection;

/**
 * Like过滤解析器
 *
 * @author Gary
 * @version 1.0
 * @date 2021-08-22
 */
public class CollectionFilterParser implements FilterParser {

    @Override
    public CharSequence parse(SqlContextManager contextManager, FilterItem filterItem) {
        SqlColumn sqlColumn = contextManager.getSqlColumn(filterItem.getFieldName());
        if (sqlColumn == null) {
            return "";
        }

        FilterSymbolEnum filterSymbol = filterItem.getSymbol();
        StringBuilder sql = new StringBuilder(sqlColumn.getFullColumn())
                .append(filterSymbol.getDesc());

        Object value = filterItem.getValue();
        sql.append("(");
        if (value != null) {
            if (value.getClass().isArray()) {
                sql.append(parseArray(contextManager, sqlColumn, (Object[]) value));
            } else if (value instanceof Collection) {
                sql.append(parseCollection(contextManager, sqlColumn, (Collection) value));
            } else {
                sql.append("?");
                contextManager.setParam(sqlColumn.getJavaType(), value);
            }
        } else {
            sql.append("null");
        }
        sql.append(")");

        return sql;
    }

    private String parseArray(SqlContextManager contextManager, SqlColumn sqlColumn, Object[] array) {
        if (array.length == 0) {
            return "null";
        }

        StringBuilder sql = new StringBuilder();
        Arrays.stream(array).forEach(value -> {
            if (sql.length() > 0) {
                sql.append(",");
            }
            sql.append("?");
            contextManager.setParam(sqlColumn.getJavaType(), value);
        });

        return sql.toString();
    }

    private String parseCollection(SqlContextManager contextManager, SqlColumn sqlColumn, Collection collection) {
        if (collection.isEmpty()) {
            return "null";
        }

        StringBuilder sql = new StringBuilder();
        collection.forEach(value -> {
            if (sql.length() > 0) {
                sql.append(",");
            }
            sql.append("?");
            contextManager.setParam(sqlColumn.getJavaType(), value);
        });

        return sql.toString();
    }

}
